/*
 * @Author: master
 * @Date: 2022-04-07 17:59:27
 * @LastEditTime: 2024-03-05 14:16:26
 * @Description: cesium 插件钩子
 */
import serveStatic from 'serve-static'; // 静态服务
const path = require('path'); // 路径服务
const fs = require('fs-extra');
const viteCesiumPlugin = () => {
  const cesiumSourcePath = 'node_modules/cesium/Build/';
  const cesiumBuildPath = 'node_modules/cesium/Build/Cesium/';
  let CESIUM_BASE_URL = 'cesium/';
  let isBuild = false; // 开发或打包模式
  let outDir = 'dist'; // 输出目录
  return {
    name: 'vite-cesium-server',
    // vite的配置
    config(config, { command }) {
      isBuild = command !== 'serve';
      // 配置输出目录
      if (config.build?.outDir) {
        outDir = config.build.outDir;
      }
      // CESIUM_BASE_URL = path.join(config.base, CESIUM_BASE_URL);
      CESIUM_BASE_URL = path.posix.join('./', CESIUM_BASE_URL);
      config.define.viteConfig.CESIUM_BASE_URL = CESIUM_BASE_URL;
      return config;
    },
    // 开发服务器的钩子
    configureServer({ middlewares }) {
      const cesiumPath = path.join(cesiumSourcePath, 'Cesium');
      // middlewares.use(path.join('/', CESIUM_BASE_URL), serveStatic(cesiumPath));
      middlewares.use(
        path.posix.join('/', CESIUM_BASE_URL),
        serveStatic(cesiumPath, {
          setHeaders: (res, path, stat) => {
            res.setHeader('Access-Control-Allow-Origin', '*');
          },
        }),
      );
    },
    // 关闭服务
    async closeBundle() {
      if (isBuild) {
        try {
          await fs.copy(path.join(cesiumBuildPath, 'Assets'), path.join(outDir, 'cesium/Assets'));
          await fs.copy(path.join(cesiumBuildPath, 'Workers'), path.join(outDir, 'cesium/Workers'));
          await fs.copy(path.join(cesiumBuildPath, 'Widgets'), path.join(outDir, 'cesium/Widgets'));
          await fs.copy(path.join(cesiumBuildPath, 'ThirdParty'), path.join(outDir, 'cesium/ThirdParty'));
        } catch (err) {
          console.error('copy failed', err);
        }
      }
    },
  };
};
export default viteCesiumPlugin;
